<template>
  <div class="pagebody">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 汇率管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="search-box">

      </div>
      <div class="handle-box">
        <el-button type="primary"
                   icon="el-icon-search"
                   @click="handleSearch">搜索</el-button>
        <el-button type="primary"
                   icon="el-icon-plus"
                   @click="handleAddNew">新建</el-button>

      </div>
      <el-table :data="tableData"
                v-loading="tableLoading"
                border
                class="table"
                ref="mainTable"
                header-cell-class-name="table-header">

        <!-- <el-table-column prop="id"
                         label="ID"
                         align="center"></el-table-column> -->
        <el-table-column label="货币类型"
                         align="center">
          <template slot-scope="props">
            <div>{{props.row.sourcecurrencyname}}<i class="el-icon-d-arrow-right"
                 style="margin:0 10px" />{{props.row.targetcurrencyname}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="rate"
                         label="汇率"
                         align="center"></el-table-column>
        <el-table-column prop="addtime"
                         label="添加时间"
                         align="center"></el-table-column>

        <el-table-column label="操作"
                         width="140"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-edit"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text"
                       icon="el-icon-delete"
                       class="color-red"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       layout="sizes, total, prev, pager, next"
                       :current-page="query.index"
                       :page-sizes="[10, 20, 30, 40, 50, 100]"
                       :page-size="query.pageSize"
                       :total="itemTotal"
                       @current-change="handlePageChange"
                       @size-change="handlePageSizeChange"></el-pagination>
      </div>
    </div>
    <el-dialog :title="editIsNewAdd?'新建汇率':'编辑汇率'"
               v-dialogDrag
               center
               :visible.sync="editVisible"
               width="60%">
      <el-form ref="form"
               :model="form"
               :rules="formRules"
               label-width="120px">

        <el-form-item label="预备货币"
                      prop="sourcecurrency">
          <el-select v-model="form.sourcecurrency"
                     class="formInput"
                     placeholder="选择货币">
            <el-option :label="nitem.name"
                       :value="nitem.id"
                       v-for="(nitem,nindex) in CurrencyDict"
                       :key="nindex"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="兑换货币"
                      prop="targetcurrency">
          <el-select v-model="form.targetcurrency"
                     class="formInput"
                     placeholder="选择货币">
            <el-option :label="nitem.name"
                       :value="nitem.id"
                       v-for="(nitem,nindex) in CurrencyDict"
                       :key="nindex"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="兑换汇率"
                      prop="rate">
          <el-input v-model="form.rate"
                    placeholder="请输入汇率"
                    maxlength="10"
                    clearable
                    class="formInput"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import API from '../../../api/index';//读入restfulAPI
import StringTool from '../../../utils/StringTool'
import JSTool from '../../../utils/JSTool'
import dataTable from './dataTable'
export default {
  name: 'currencyExchangeRate',
  mixins: [dataTable],
  data () {
    let CheckDigit = (rule, value, callback) => {
      if (!StringTool.DigitNumber(String(value))) {
        return callback(new Error('只能为整数和保留两位小数'));
      }
      if (Number(value) < 0) {
        return callback(new Error('只能为正数'));
      }
      callback();
    };
    let CheckFormDetail = (rule, value, callback) => {

      if (!value || value.length <= 0) {
        return callback(new Error('至少需要一个代理'));
      }
      for (let i = 0; i < value.length; i++) {
        if (value[i].courierId == null) {
          return callback(new Error('代理快递不能为空'));
        }
        for (let j = i + 1; j < value.length; j++) {
          if (value[j].courierId == value[i].courierId) {
            return callback(new Error('代理快递不能重复'));
          }

        }
      }
      callback();
    };
    return {
      searchSet: {
      },
      query: {
        status: 1,
        index: 1,
        pageSize: 10
      },
      editVisible: false,
      editIsNewAdd: false,

      CurrencyDict: [],
      form: {
        sourcecurrency: null,
        targetcurrency: null,
        rate: 0,
      },
      formRules: {
        sourcecurrency: [
          { required: true, message: '参数不能为空', trigger: 'blur' },
        ],
        targetcurrency: [
          { required: true, message: '参数不能为空', trigger: 'blur' },
          { validator: (rule, value, callback) => { return value == this.form.sourcecurrency ? callback(new Error('兑换货币类型不能相同')) : callback(); }, trigger: 'blur' },
        ],
        rate: [
          { validator: CheckDigit, required: true, trigger: 'change' }
        ],
      }
    };
  },
  created () {
    this.init()
  },
  mounted () {
  },
  methods: {

    //页面初始化
    init () {
      API.StandardDoWith(API.Currency.Get({ status: 1 }), this, {
        success: (detail) => {
          let dict = {}
          detail.map(it => {
            dict[it.id] = it
          })
          this.CurrencyDict = dict;
        },
      })
      this.getData();
    },


    getData () {
      this.tableLoading = true
      API.StandardDoWith(API.ExchangeRate.Get(this.getQuery()), this, {
        success: (detail) => {
          this.tableData = detail.list;
          this.itemTotal = detail.count
        },
        complete: () => {
          this.tableLoading = false
        }
      })
    },

    handleAddNew () {
      this.editVisible = true;
      this.editIsNewAdd = true;
      this.form = {
        sourcecurrency: null,
        targetcurrency: null,
        rate: 0,
      }

    },



    // 编辑操作
    handleEdit (index, row) {
      this.form = JSTool.DeepClone(row)
      this.editIsNewAdd = false;
      this.editVisible = true;
    },

    handleDelete (index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          API.StandardDoWith(API.ExchangeRate.Delete({ id: row.id }), this, {
            success: (detail) => {
              this.$message.success(`成功删除`);
              this.getData()
            },
          })
        })
        .catch(() => { });

    },
    saveEdit () {
      this.$refs.form.validate((valid) => {
        if (valid) {

          this.form.rate = Number(this.form.rate)
          let net = this.editIsNewAdd ? API.ExchangeRate.Post(this.form) : API.ExchangeRate.Put(this.form)
          API.StandardDoWith(net, this, {
            success: (detail) => {
              this.editVisible = false;
              this.$message.success(`成功提交`);
              this.getData()
            },
          })
        } else {
          this.$message.error(`表单验证失败，无法提交`);
          return false;
        }
      });
    },


  }
};
</script>

<style scoped>
@import '../../../assets/css/dataTable.css';
</style>
